import requests
import json
from res import *

# 全局变量，用于存储歌曲列表和下载链接
global_song_list = []
global_mp3_url = None

clear_screen()
title()

def download_file(url, save_path):
    try:
        # 发送 GET 请求
        response = requests.get(url, stream=True)
        response.raise_for_status()  # 检查请求是否成功

        # 打开文件并写入内容
        with open(save_path, 'wb') as file:
            for chunk in response.iter_content(chunk_size=8192):  # 每次写入 8KB
                file.write(chunk)
        print_b(f"文件已成功下载到 {save_path}")
        print_b(f'感谢使用!\n如果下载失败请复制此链接到浏览器下载:{url}')
        input_g('按回车键返回---->')
        clear_screen()
        os.system(f"{p()} main.py")
        exit()
    except requests.exceptions.RequestException as e:
        print_r(f"下载失败：{e}")
        print_b('感谢使用!')
        input_g('按回车键返回---->')
        clear_screen()
        os.system(f"{p()} main.py")
        exit()

def get_mp3_download_link(song_hash):
    api_url = f"http://m.kugou.com/app/i/getSongInfo.php?cmd=playInfo&hash={song_hash}"
    try:
        # 发送请求到API网址
        response = requests.get(api_url)
        response.raise_for_status()  # 检查请求是否成功
        data = response.json()

        # 从返回的JSON数据中提取MP3下载链接
        if 'url' in data and data['url']:
            mp3_url = data['url']
        else:
            mp3_url = None

        if mp3_url:
            print_b(f"提取的MP3下载链接: {mp3_url}")
            print_b('开始自动下载...')
        else:
            print_r("未找到MP3下载链接,歌曲为付费")
            input_g('按回车键返回---->')
            clear_screen()
            os.system(f"{p()} main.py")
            exit()
    except requests.RequestException as e:
        print_r(f"请求失败: {e}")
        input_g('按回车键返回---->')
        clear_screen()
        os.system(f"{p()} main.py")
        exit()
    except json.JSONDecodeError as e:
        print_r(f"解析JSON失败: {e}")
        input_g('按回车键返回---->')
        clear_screen()
        os.system(f"{p()} main.py")
        exit()
    except KeyError as e:
        print_r(f"JSON数据中缺少必要的字段: {e}")
        input_g('按回车键返回---->')
        clear_screen()
        os.system(f"{p()} main.py")
        exit()
    return mp3_url

def get_song_list(song_name):
    global global_song_list
    search_url = "http://mobilecdn.kugou.com/api/v3/search/song"
    params = {
        "format": "json",
        "keyword": song_name,
        "page": 1,
        "pagesize": 10  # 获取前10个结果
    }

    try:
        response = requests.get(search_url, params=params)
        response.raise_for_status()  # 检查请求是否成功
        data = response.json()

        # 检查是否有搜索结果
        if data["data"]["total"] > 0:
            global_song_list = data["data"]["info"]
            print_b("找到以下歌曲：")
            for index, song in enumerate(global_song_list):
                print_b(f"{index + 1}. {song['songname']} - {song['singername']} (哈希值: {song['hash']})")
        else:
            print_r(f"未找到歌曲: {song_name}")
            input_g('按回车键返回---->')
            clear_screen()
            os.system(f"{p()} main.py")
            exit()
    except requests.RequestException as e:
        print_r(f"请求失败: {e}")
        input_g('按回车键返回---->')
        clear_screen()
        os.system(f"{p()} main.py")
        exit()
    except KeyError as e:
        print_r(f"解析数据失败: {e}")
        input_g('按回车键返回---->')
        clear_screen()
        os.system(f"{p()} main.py")
        exit()

def main():
    song_name = input_g("请输入酷狗音乐歌曲名: ")
    save_path = input_g('请输入下载路径，默认为当前文件夹下的music文件夹:')
    if save_path != '':
        if os.path.exists(save_path):
            pass
        else:
            print_r("路径不存在,已使用默认下载路径")
            save_path = ''
    else:
        pass
    if save_path == '':
        save_path = 'music/酷狗音乐'

    get_song_list(song_name)

    if global_song_list:
        try:
            choice = int(input_g("请输入要下载的歌曲序号: "))
            if 1 <= choice <= len(global_song_list):
                selected_song = global_song_list[choice - 1]
                song_hash = selected_song['hash']
                song_name = selected_song['songname']
                song_name = song_name.replace("/", "_")  # 替换文件名中的非法字符
                save_path = os.path.join(save_path, f"[酷狗]{song_name}.mp3")
                mp3_url = get_mp3_download_link(song_hash)
                if mp3_url:
                    download_file(mp3_url, save_path)
            else:
                print_r("无效的序号")
                input_g('按回车键返回---->')
                clear_screen()
                os.system(f"{p()} kugou.py")
                exit()
        except ValueError:
            print_r("请输入有效的数字序号")
            input_g('按回车键返回---->')
            clear_screen()
            os.system(f"{p()} kugou.py")
            exit()
    else:
        print_r('未找到歌曲，请确认歌曲是否存在。')
        input_g('按回车键返回---->')
        clear_screen()
        os.system(f"{p()} kugou.py")
        exit()

if __name__ == "__main__":
    main()